var queryClassTermReportUrl = basePath + "/sys/student/termReport/json/queryClassTermReport";
var batchCreatePdfUrl = basePath + "/sys/student/termReport/json/batchCreate";
var updateStudentTermReport = basePath + "/sys/student/termReport/json/updateStudentTermReport";


/**
 * @author huhekun
 * @date 2020/1/8
 * @description 这个备份js的作用是修改了表格的数据，因为有新的表格数据格式（期末登分表总表Excel），修改后用这个
 */

var dataGrid;
var schoolId = $("#userSchoolId").val();

$(function () {
    initSchoolIdInputValue();
    initTermList();
    $('#files').filebox({
        buttonText: '选择文件',
        buttonAlign: 'left'
    })
});

function initSchoolIdInputValue() {
    var v1 = $("#userSchoolId").val();
    $("#schoolId").val(v1);
}

function loadData() {
    dataGrid = $('#studentDg').datagrid({
        url: queryClassTermReportUrl,
        toolbar: '#tb',
        fit: true,
        fitColumns: true,
        border: true,
        pagination: false,
        idField: 'id',
        pageSize: config.pageSize,
        autoRowHeight: 140,
        pageList: config.pageList,
        nowrap: true,
        striped: true,
        singleSelect: true,
        rownumbers: true,
        collapsible: true,
        queryParams: {
            termId: $("#termId").val(),
            grade: $("#grade").val(),
            clazz: $("#clazz").val(),
            schoolId: schoolId
        },
        frozenColumns: [[{
            field: 'id',
            checkbox: false,
            hidden: true
        }, {
            field: 'studentNum',
            title: '学号',
        }, {
            field: 'studentName',
            title: '学生姓名',
        }]],
        columns: [[
            {
                field: 'chinese',
                title: '语文基础',
                editor: {type: 'textbox'}
            }
            , {
                field: 'read2',
                title: '阅读积累',
                editor: {type: 'textbox'}
            }
            , {
                field: 'math',
                title: '数学',
                editor: {type: 'textbox'}
            }
            , {
                field: 'calculate',
                title: '计算能力',
                editor: {type: 'textbox'}
            }
            , {
                field: 'english',
                title: '英语PEP',
                editor: {type: 'textbox'}
            }
            , {
                field: 'longman',
                title: '朗文',
                editor: {type: 'textbox'}
            }
            , {
                field: 'englishLanguage',
                title: '英语口语',
                editor: {type: 'textbox'}
            }
            , {
                field: 'quality',
                title: '道德法制',
                editor: {type: 'textbox'}
            }
            , {
                field: 'sports',
                title: '体育',
                editor: {type: 'textbox'}
            }
            , {
                field: 'music',
                title: '音乐',
                editor: {type: 'textbox'}
            }
            , {
                field: 'theatre',
                title: '戏剧',
                editor: {type: 'textbox'}
            }
            , {
                field: 'arts',
                title: '美术',
                editor: {type: 'textbox'}
            }
            , {
                field: 'calligraphy',
                title: '书法',
                editor: {type: 'textbox'}
            }
            , {
                field: 'science',
                title: '科学',
                editor: {type: 'textbox'}
            }
            , {
                field: 'infomation',
                title: '信息',
                editor: {type: 'textbox'}
            }
            , {
                field: 'steam',
                title: 'steam',
                editor: {type: 'textbox'}
            }
            , {
                field: 'appraising',
                title: '评优',
                width: 200,
                editor: {type: 'textbox'},
                formatter: function (value, row, index) {
                    return '<span title="' + value + '" class="note">' + value!=null?value:'' + '</span>';
                }
            }
            , {
                field: 'comment',
                title: '期末评语',
                width: 200,
                editor: {type: 'textbox'},
                formatter: function (value, row, index) {
                    return '<span title="' + value + '" class="note">' + value!=null?value:'' + '</span>';
                }
            }
            , {
                field: 'schoolPrize',
                title: '校内奖项',
                width: 200,
                editor: {type: 'textbox'},
                formatter: function (value, row, index) {
                    return '<span title="' + value + '" class="note">' + value!=null?value:'' + '</span>';
                }
            }
        ]],
        onLoadSuccess: function (data) {
            $(".note").tooltip({
                onShow: function () {
                    $(this).tooltip('tip').css({
                        borderColor: '#000'
                    });
                }
            });
        },
        onAfterEdit: function (rowIndex, rowData, changes) {
            if (rowData.id) {
                changes.id = rowData.id;
                changes.schoolId = schoolId;
                addmodify(changes)
            }
        }

    });
}

function reload() {
    dataGrid.datagrid("clearSelections");
    dataGrid.datagrid('load');
}

function searchForm(formId) {
    dataGrid.datagrid('load', $.serializeObject($('#' + formId)));
}

function resetForm(formId) {
    $("#" + formId)[0].reset();
}

function initGradeList(termName) {
    var termYear = termName.substring(0, termName.indexOf("-"))
    $.ajax({
        url: basePath + "/gradeByTermYear",
        type: "post",
        dataType: "json",
        data: {
            termYear: termYear
        },
        async: false,
        success: function (data) {
            var html = '';
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    html += "<option value='" + i + "'>" + data[i] + "</option>";
                }
                ;
            }
            $("#grade").html(html);
            $("#grade").trigger("onchange");
        }, error: function () {
            alert("查询年级异常");
        }
    });
}

function searchGrade() {
    initGradeList($("#termId option:selected")[0].text);
}

function searchClazz(grade) {
    if (!grade) return
    $.ajax({
        url: basePath + "/getFullClazz?grade=" + grade,
        type: "GET",
        dataType: "json",
        async: false,
        success: function (data) {
            var html = '';
            for (var i in data) {
                if (data.hasOwnProperty(i)) {
                    html += "<option value='" + data[i] + "'>" + data[i] + "班</option>";
                }
                ;
            }
            $("#clazz").html(html);
            if (!dataGrid) {
                loadData();
            }
        }, error: function () {
            alert("查询班级异常");
        }
    });
}


function initTermList() {
    $.ajax({
        url: basePath + "/termList",
        type: 'POST',
        dataType: 'json',
        error: function (data) {
            $.messager.progress('close');
            $.messager.alert('系统提示', data.msg, 'error');
        },
        success: function (data) {
            var html = "";
            for (var i in data) {
                html += "<option value='" + data[i].id + "'>" + data[i].termName + "</option>";
            }
            $("#termId").html(html);
            initGradeList(data[0].termName);
        }
    });
}

var uploadBox;

function upload() {
    var termId = $("#termId option:selected")[0].text;
    var grade = $("#grade option:selected")[0].text;
    var clazz = $("#clazz option:selected")[0].text;
    var schoolId = schoolId;
    $("#scoreTips").html("<span class='calendar-sunday'>确认选择上传" + termId + grade + "(" + clazz + ")成绩，以免成绩上传出错</span>");
    uploadBox = $('#uploadBox').dialog({
        title: '上传期末成绩报告',
        modal: true,
        width: 400,
        top: 200,
        draggable: true,
        resizable: true,
        buttons: '#btns',
        onClose: function () {
            $('#files').filebox('setValue', '');
        }
    }).show();
}

function uploadCommit() {
    var fileObj = document.getElementById('filebox_file_id_2').files[0];
    if (!fileObj) {
        $.messager.alert('提醒', '请选择文件');
        return;
    }
    $.messager.progress({
        title: '提示',
        msg: '上传中，请稍候...'
    });
    var xhr = new XMLHttpRequest();
    xhr.open('POST', basePath + "/sys/report/classTermReport/import");
    xhr.onload = function () {
        if (xhr.status === 200) {
            $.messager.progress('close');
            var resp = JSON.parse(xhr.response);
            if (resp.code == '000') {
                $.messager.alert("成功", "上传成功！", "info");
                reload();
                $('#files').filebox('setValue', '');
                uploadBox.dialog('close');
            } else {
                $.messager.alert('错误提醒', resp.msg);
            }
        }
    };
    xhr.onerror = function () {
        $.messager.progress('close');
        $.messager.alert('错误', "上传异常");
    };
    var fd = new FormData();
    fd.append('files', fileObj);
    fd.append("termId", $("#termId").val());
    fd.append("termType", $("#termType").val());
    fd.append("grade", $("#grade").val());
    fd.append("clazz", $("#clazz").val());
    fd.append("schoolId", schoolId);
    // 触发上传
    setTimeout(function () {
        xhr.send(fd);
    }, 1000)
}

var cleanFormPanel = function (formId) {
    $('#' + formId)[0].reset();
}

function save(id) {
    if (dgEditIndex[id] != null) {
        $('#' + id).datagrid('endEdit', dgEditIndex[id]);
        dgEdit[id] = null;
    }
}

function addmodify(data) {
    $.ajax({
        type: "POST",
        url: updateStudentTermReport,
        data: data,
        success: function (res) {
            if (res.code == '000') {
                reload();
                $.messager.alert('提示', '提交成功', 'info');
            } else {
                $.messager.alert('提示', '提交失败', 'error');
                errorEdit("studentDg");
            }
        },
        error: function () {
            alert("提交异常");
            errorEdit("studentDg");
        }
    });
}

function exportToExcel(searchForm, exportUrl) {
    $("#" + searchForm).attr('action', exportUrl);
    $("#" + searchForm).submit();
}

/**
 * @author huhekun
 * @description 导出页面表格数据到Excel
 */
function downloadExcel() {
    var basePath = window.document.location.pathname.substring(0, window.document.location.pathname.substr(1).indexOf('/') + 1);
    var termId = $('#termId').val();	//学期ID
    var grade = $("#grade").val();		//年纪
    var clazz = $("#clazz").val();		//班级
    $("#studentSearchForm").attr('action', basePath + '/sys/report/studentFianlTermScoreReport/export');
    $("#studentSearchForm").submit();
}